/**
 * @Author: hiram
 * @Date: 2021/12/10 下午 01:33
 */
package main

import (
	"gitee.com/gbat/nats-demo/common"
	"github.com/nats-io/nats.go"
	"log"
	"time"
)

func main() {
	opts := []nats.Option{nats.Name("NATS Sample Queue Subscriber")}
	opts = common.SetupConnOptions(opts)
	// Connect to NATS
	nc, err := nats.Connect(nats.DefaultURL, opts...)
	if err != nil {
		log.Fatalln(err)
	}

	// Create JetStream Context
	js, err := nc.JetStream(nats.PublishAsyncMaxPending(256))
	if err != nil {
		log.Fatalln(err)
	}

	//Add stream
	_, err = js.AddStream(&nats.StreamConfig{
		Name:     common.DefaultStreamName,
		Subjects: []string{common.DefaultSubject, common.DefaultSubject2},
		MaxMsgs:  4,
	})
	if err != nil {
		log.Fatalln(err)
	}

	//Simple Stream Publisher
	ack, err := js.Publish(common.DefaultSubject, []byte("hello_"+time.Now().String()), nats.ExpectStream(common.DefaultStreamName))
	if err != nil {
		log.Fatalln(err)
	}
	log.Println(ack.Sequence)
	ack2, err := js.Publish(common.DefaultSubject2, []byte("hello_"+time.Now().String()), nats.ExpectStream(common.DefaultStreamName))
	if err != nil {
		log.Fatalln(err)
	}
	log.Println(ack2.Sequence)
	//err = js.DeleteMsg(common.DefaultStreamName,11)
	//if err!=nil{
	//  log.Fatalln(err)
	//}
	time.Sleep(time.Hour)
	// Simple Async Stream Publisher
	//for i := 0; i < 500; i++ {
	//    _, err := js.PublishAsync("ORDERS.scratch", []byte("hello"))
	//    if err!=nil{
	//        log.Fatalln(err)
	//    }else{
	//        log.Printf("finished:%d \n",i)
	//    }
	//
	//}
	//select {
	//case <-js.PublishAsyncComplete():
	//    log.Println("all finished")
	//case <-time.After(5 * time.Second):
	//    log.Println("Did not resolve in time")
	//}

	//jc, err := nc.JetStream()
	//if err != nil {
	//    log.Println(err)
	//}
	//jc.AddStream(&nats.StreamConfig{
	//    Name:     "TEST",
	//    Subjects: []string{"TEST.111", "TEST.222"},
	//})
	//log.Println(jc.StreamInfo("TEST"))
	//
	//i :=0
	//nc.QueueSubscribe(common.DefaultSubject, common.DefaultQueue, func(msg *nats.Msg) {
	//    i++
	//    printMsg(msg, i)
	//})
	//nc.Flush()
	//
	//if err := nc.LastError(); err != nil {
	//    log.Fatal(err)
	//}
	//
	//log.Printf("Listening on [%s], queue group [%s]", common.DefaultSubject, common.DefaultQueue)
	//log.SetFlags(log.LstdFlags)
}
